<template>
  <div class="product-detail-container" v-loading="loading">
    <div class="product-detail-content" v-if="product">
      <div class="product-gallery">
        <el-carousel :interval="4000" type="card" height="400px">
          <el-carousel-item v-for="(image, index) in productImages" :key="index">
            <img :src="image" class="gallery-image" />
          </el-carousel-item>
        </el-carousel>
      </div>

      <div class="product-info">
        <div class="product-header">
          <h1 class="product-name">{{ product.name }}</h1>
          <div class="product-tags" v-if="product.isNew || product.isHot">
            <el-tag v-if="product.isNew" type="primary" effect="plain" size="small">新品</el-tag>
            <el-tag v-if="product.isHot" type="danger" effect="plain" size="small">热销</el-tag>
          </div>
        </div>

        <div class="product-price-container">
          <div class="price-row">
            <span class="price-label">价格</span>
            <span class="current-price">¥{{ product.price }}</span>
            <span class="original-price" v-if="product.originalPrice">¥{{ product.originalPrice }}</span>
            <span class="discount" v-if="product.originalPrice">
              {{ Math.round((1 - product.price / product.originalPrice) * 100) }}% OFF
            </span>
          </div>
        </div>

        <div class="product-sales">
          <span>销量: {{ product.sales }}件</span>
        </div>

        <div class="product-quantity">
          <span class="quantity-label">数量</span>
          <el-input-number v-model="quantity" :min="1" :max="99" size="large" />
        </div>

        <div class="product-actions">
          <el-button type="primary" size="large" @click="addToCart">
            <el-icon>
              <ShoppingCart />
            </el-icon>
            加入购物车
          </el-button>
          <el-button type="danger" size="large" @click="buyNow">
            立即购买
          </el-button>
          <el-button size="large" @click="toggleFavorite">
            <el-icon>
              <Star v-if="!isFavorite" />
              <StarFilled v-else />
            </el-icon>
            {{ isFavorite ? '已收藏' : '收藏' }}
          </el-button>
        </div>

        <div class="product-service">
          <div class="service-item">
            <el-icon>
              <Checked />
            </el-icon>
            <span>正品保证</span>
          </div>
          <div class="service-item">
            <el-icon>
              <Checked />
            </el-icon>
            <span>7天无理由退货</span>
          </div>
          <div class="service-item">
            <el-icon>
              <Checked />
            </el-icon>
            <span>48小时发货</span>
          </div>
        </div>
      </div>
    </div>

    <div class="product-tabs">
      <el-tabs type="border-card">
        <el-tab-pane label="商品详情">
          <div class="product-description">
            <h2>产品详情</h2>
            <div class="description-content">
              <p>这是一款高性能、高品质的产品，采用先进的技术和优质的材料制造而成。具有以下特点：</p>
              <ul>
                <li>高性能处理器，运行速度快</li>
                <li>长效电池，持久续航</li>
                <li>精美外观设计，手感舒适</li>
                <li>多功能集成，满足各种需求</li>
              </ul>
              <p>无论是工作还是娱乐，都能为您提供出色的体验。</p>

              <div class="detail-images">
                <div v-if="detailImages.length > 0">
                  <img v-for="(image, index) in detailImages" :key="index" :src="image" class="detail-image" />
                </div>
                <div v-else class="no-images">
                  <el-empty description="暂无详情图片" />
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="规格参数">
          <div class="product-specs">
            <h2>规格参数</h2>
            <el-table :data="specsList" style="width: 100%">
              <el-table-column prop="name" label="参数名称" width="180" />
              <el-table-column prop="value" label="参数值" />
            </el-table>
          </div>
        </el-tab-pane>

        <el-tab-pane label="用户评价">
          <div class="product-reviews">
            <h2>用户评价</h2>
            <div class="review-stats">
              <div class="rating">
                <span class="rating-value">4.8</span>
                <div class="stars">
                  <el-icon v-for="i in 5" :key="i">
                    <StarFilled />
                  </el-icon>
                </div>
                <span class="rating-count">共 128 条评价</span>
              </div>
            </div>

            <div class="review-list">
              <div v-for="(review, index) in reviews" :key="index" class="review-item">
                <div class="review-header">
                  <el-avatar :size="40" :src="review.avatar" />
                  <div class="review-user">
                    <div class="review-username">{{ review.username }}</div>
                    <div class="review-rating">
                      <el-icon v-for="i in 5" :key="i" :color="i <= review.rating ? '#F7BA2A' : '#C0C4CC'">
                        <StarFilled />
                      </el-icon>
                      <span class="review-date">{{ review.date }}</span>
                    </div>
                  </div>
                </div>
                <div class="review-content">{{ review.content }}</div>
                <div class="review-images" v-if="review.images && review.images.length > 0">
                  <el-image v-for="(image, imgIndex) in review.images" :key="imgIndex" :src="image"
                    :preview-src-list="review.images" class="review-image" />
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 推荐商品 -->
    <div class="recommendations">
      <h3 class="section-title">相关推荐</h3>
      <el-row :gutter="20">
        <el-col :xs="12" :sm="8" :md="6" :lg="4" v-for="item in relatedProducts" :key="item.id">
          <product-card :product="item" />
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Star, StarFilled, ShoppingCart, Checked } from '@element-plus/icons-vue'
import ProductCard from '@/components/ProductCard.vue'
import request from '@/utils/request'

const route = useRoute()
const router = useRouter()
const loading = ref(true)
const product = ref(null)
const quantity = ref(1)
const isFavorite = ref(false)

// 商品图片
const productImages = computed(() => {
  if (!product.value) return []

  // 只使用后端返回的mainImage作为图片
  return product.value.mainImage ? [product.value.mainImage] : []
})

// 详情图片
const detailImages = ref([])

// 获取商品详情图片
const fetchDetailImages = async (productId) => {
  try {
    const res = await request.get(`/products/${productId}/images/2`) // 类型2表示详情图
    if (res.code === 200 && res.data) {
      // 从返回的数据中提取图片URL
      detailImages.value = res.data.map(item => item.imageUrl)
    }
  } catch (error) {
    console.error('获取商品详情图片失败:', error)
  }
}

// 规格参数
const specsList = [
  { name: '品牌', value: '根据商品自动填充' },
  { name: '型号', value: '根据商品自动填充' },
  { name: '颜色', value: '黑色/白色/金色' },
  { name: '尺寸', value: '根据商品自动填充' },
  { name: '重量', value: '根据商品自动填充' },
  { name: '保修期', value: '12个月' }
]

// 用户评价
const reviews = [
  {
    username: '用户123456',
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    rating: 5,
    date: '2024-03-15',
    content: '非常好用的产品，外观精美，性能强劲，非常满意这次购买！',
    images: [
      'https://img.alicdn.com/imgextra/i4/O1CN01Qg1L2L1aEEYLCJYQK_!!6000000003294-0-tps-800-800.jpg'
    ]
  },
  {
    username: '快乐购物者',
    avatar: 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png',
    rating: 4,
    date: '2024-03-10',
    content: '商品质量不错，就是发货有点慢，其他都挺好的。'
  },
  {
    username: '科技爱好者',
    avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
    rating: 5,
    date: '2024-03-05',
    content: '性价比很高，各方面都很满意，会推荐给朋友购买！',
    images: [
      'https://img.alicdn.com/imgextra/i3/O1CN01FQW2Oa1vfGEX3vOjI_!!6000000006205-0-tps-800-800.jpg',
      'https://img.alicdn.com/imgextra/i1/O1CN01Bd6Lw11Ux0LWGOoXl_!!6000000002581-0-tps-800-800.jpg'
    ]
  }
]

// 相关推荐
const relatedProducts = ref([]);

// 获取推荐商品
const fetchRelatedProducts = async () => {
  try {
    const res = await request.get('/products/recommend', {
      params: { limit: 6 }
    });

    if (res.code === 200 && res.data) {
      relatedProducts.value = res.data;
    }
  } catch (error) {
    console.error('获取推荐商品失败:', error);
  }
};

// 获取商品详情
const fetchProductDetail = async () => {
  loading.value = true;

  try {
    // 从后端API获取商品详情
    const id = parseInt(route.params.id);
    const res = await request.get(`/products/${id}`);

    if (res.code === 200 && res.data) {
      product.value = res.data;

      // 更新规格参数
      if (product.value.brandName) {
        specsList[0].value = product.value.brandName;
      }

      specsList[1].value = product.value.name.split(' ')[1] || '标准版';

      // 获取详情图片
      await fetchDetailImages(product.value.id);

      // 检查收藏状态
      await checkFavoriteStatus();
    } else {
      ElMessage.error('获取商品详情失败');
    }
  } catch (error) {
    console.error('获取商品详情失败:', error);
    ElMessage.error('获取商品详情失败');
  } finally {
    loading.value = false;
  }
}

// 添加到购物车
const addToCart = async () => {
  if (!product.value) return

  try {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')

    if (!userInfo.id) {
      // 如果未登录，使用localStorage
      const cartItems = JSON.parse(localStorage.getItem('cartItems') || '[]')
      const existingItem = cartItems.find(item => item.id === product.value.id)

      if (existingItem) {
        existingItem.quantity += quantity.value
      } else {
        cartItems.push({
          id: product.value.id,
          name: product.value.name,
          price: product.value.price,
          mainImage: product.value.mainImage,
          quantity: quantity.value
        })
      }

      localStorage.setItem('cartItems', JSON.stringify(cartItems))
      window.emitter?.emit('cart-updated')
      ElMessage.success('已添加到购物车')
      return
    }

    // 如果已登录，调用后端API
    const cartData = {
      userId: userInfo.id,
      productId: product.value.id,
      quantity: quantity.value
    }

    await request.post('/cart', cartData)
    window.emitter?.emit('cart-updated')
    ElMessage.success('已添加到购物车')
  } catch (error) {
    console.error('添加到购物车失败:', error)
    ElMessage.error('添加到购物车失败')
  }
}

// 立即购买
const buyNow = () => {
  addToCart()
  router.push('/home/cart')
}

// 检查收藏状态
const checkFavoriteStatus = async () => {
  try {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    if (!userInfo.id || !product.value) {
      return
    }

    const res = await request.get('/favorites/check', {
      params: {
        userId: userInfo.id,
        productId: product.value.id
      }
    })
    if (res.code === 200) {
      isFavorite.value = res.data
    }
  } catch (error) {
    console.error('检查收藏状态失败:', error)
  }
}

// 切换收藏状态
const toggleFavorite = async () => {
  try {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    if (!userInfo.id) {
      ElMessage.warning('请先登录')
      return
    }

    console.log('发送收藏请求:', { userId: userInfo.id, productId: product.value.id })

    // 使用toggle接口，更简单可靠
    const res = await request.post('/favorites/toggle', {
      userId: userInfo.id,
      productId: product.value.id
    })

    console.log('收藏请求响应:', res)

    if (res.code === 200) {
      isFavorite.value = res.data // 后端返回新的收藏状态
      if (isFavorite.value) {
        ElMessage.success('已添加到收藏夹')
      } else {
        ElMessage.info('已从收藏夹移除')
      }
    } else {
      ElMessage.error(res.message || '收藏操作失败')
    }
  } catch (error) {
    console.error('收藏操作失败:', error)
    ElMessage.error('收藏操作失败')
  }
}

onMounted(async () => {
  // 滚动到页面顶部
  const mainEl = document.querySelector('.el-main')
  if (mainEl) {
    mainEl.scrollTop = 0
  }
  window.scrollTo(0, 0)

  fetchProductDetail()
  fetchRelatedProducts()
})
</script>

<style scoped>
.product-detail-container {
  padding: 20px;
}

.product-detail-content {
  display: flex;
  gap: 30px;
  margin-bottom: 30px;
}

.product-gallery {
  width: 50%;
}

.gallery-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.product-info {
  width: 50%;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.product-header {
  margin-bottom: 10px;
}

.product-name {
  font-size: 24px;
  font-weight: 600;
  margin: 0 0 10px;
}

.product-tags {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.product-price-container {
  background-color: #f8f8f8;
  padding: 15px;
  border-radius: 8px;
}

.price-row {
  display: flex;
  align-items: center;
  gap: 10px;
}

.price-label {
  font-size: 14px;
  color: #909399;
}

.current-price {
  font-size: 24px;
  font-weight: bold;
  color: #F56C6C;
}

.original-price {
  font-size: 14px;
  color: #909399;
  text-decoration: line-through;
}

.discount {
  font-size: 12px;
  color: #fff;
  background-color: #F56C6C;
  padding: 2px 6px;
  border-radius: 4px;
}

.product-sales {
  color: #909399;
  font-size: 14px;
}

.product-quantity {
  display: flex;
  align-items: center;
  gap: 15px;
}

.quantity-label {
  font-size: 14px;
  color: #606266;
}

.product-actions {
  display: flex;
  gap: 15px;
  margin-top: 10px;
}

.product-service {
  margin-top: 20px;
  display: flex;
  gap: 20px;
}

.service-item {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 14px;
  color: #606266;
}

.product-tabs {
  margin-bottom: 30px;
}

.product-description,
.product-specs,
.product-reviews {
  padding: 20px 0;
}

.product-description h2,
.product-specs h2,
.product-reviews h2 {
  font-size: 18px;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #EBEEF5;
}

.description-content {
  font-size: 14px;
  line-height: 1.6;
  color: #606266;
}

.description-content p {
  margin-bottom: 15px;
}

.description-content ul {
  padding-left: 20px;
  margin-bottom: 15px;
}

.detail-images {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.detail-image {
  width: 100%;
  border-radius: 8px;
}

.review-stats {
  margin-bottom: 20px;
}

.rating {
  display: flex;
  align-items: center;
  gap: 10px;
}

.rating-value {
  font-size: 24px;
  font-weight: bold;
  color: #F7BA2A;
}

.stars {
  display: flex;
  color: #F7BA2A;
}

.rating-count {
  font-size: 14px;
  color: #909399;
}

.review-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.review-item {
  padding: 15px;
  border-bottom: 1px solid #EBEEF5;
}

.review-header {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}

.review-user {
  display: flex;
  flex-direction: column;
}

.review-username {
  font-weight: 500;
  margin-bottom: 5px;
}

.review-rating {
  display: flex;
  align-items: center;
  gap: 5px;
}

.review-date {
  font-size: 12px;
  color: #909399;
  margin-left: 10px;
}

.review-content {
  margin-bottom: 10px;
  line-height: 1.6;
}

.review-images {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.review-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  cursor: pointer;
}

.recommendations {
  margin-top: 30px;
}

.section-title {
  font-size: 18px;
  margin-bottom: 20px;
  position: relative;
  padding-left: 15px;
}

.section-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 18px;
  background-color: #409EFF;
  border-radius: 2px;
}

@media (max-width: 768px) {
  .product-detail-content {
    flex-direction: column;
  }

  .product-gallery,
  .product-info {
    width: 100%;
  }
}
</style>